import logging

from PyQt5.QtWidgets import *
import os
from view import ui_mainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from common import dbcontrol


class mainControl(QtWidgets.QMainWindow):
    logger = None

    def __init__(self):
        self.logger = logging.getLogger("applog")
        QtWidgets.QMainWindow.__init__(self)
        self.ui = ui_mainWindow.Ui_MainWindow()
        self.ui.setupUi(self)
        # 初始化设置数据
        self.__initSetupData()
        # 选择打卡机excel
        self.ui.selCheckFile.clicked.connect(self.select_file)
        # 导入打卡机
        self.ui.checkInput.clicked.connect(self.importFile)
        # 选择请假excel
        self.ui.selRestFile.clicked.connect(self.select_file)
        # 导入微信
        self.ui.restInput.clicked.connect(self.importFile)
        # 绑定工作日日历控件事件
        self.ui.workCale.selectionChanged.connect(self.addSetupDate)
        self.ui.holidayCale.selectionChanged.connect(self.addSetupDate)
        # 新增例会人员
        self.ui.addPerson.clicked.connect(self.addSetupDate)
        # 删除特殊工作日
        self.ui.workList.itemDoubleClicked.connect(self.removeDate)
        # 删除特殊假日
        self.ui.holidayList.itemDoubleClicked.connect(self.removeDate)
        # 删除例会人员
        self.ui.personList.itemDoubleClicked.connect(self.removeDate)
        # 清空
        self.ui.workClearBtn.clicked.connect(self.clear)
        self.ui.holidayClearBtn.clicked.connect(self.clear)
        self.ui.personClearBtn.clicked.connect(self.clear)
        # 保存特殊工作日
        self.ui.saveWorkDaysBtn.clicked.connect(self.saveData)
        # 保存特殊假日
        self.ui.saveHolidaysBtn.clicked.connect(self.saveData)
        # 保存例会人员
        self.ui.savePersonBtn.clicked.connect(self.saveData)
        #  ******* 输出结果excel********
        self.ui.resOutput.clicked.connect(self.outputResult)

    # 导入文件
    def importFile(self):
        objName = self.sender().objectName()
        if objName == 'checkInput':
            filePath = self.findChild(QLineEdit, 'checkFilePath')
        else:
            filePath = self.findChild(QLineEdit, 'restFilePath')

        pathStr = filePath.text()
        if pathStr == None or pathStr == '':
            QMessageBox.warning(self, '警告', '请先选择请假文件,再进行导入操作', QMessageBox.Yes)
            return
        else:
            if objName == 'checkInput':
                flag = dbcontrol.handleCheckData(pathStr)
            else:
                flag = dbcontrol.handleRestData(pathStr)

        if flag == None:
            QMessageBox.information(self, '消息', f'文件导入失败！', QMessageBox.Yes)
        else:
            QMessageBox.information(self, '消息', f'文件导入成功,成功导入{flag}条数据', QMessageBox.Yes)

    # 保存
    def saveData(self):
        objName = self.sender().objectName()
        # 工作日 = 1  假期 = 2   人员 = 3
        if objName == 'saveWorkDaysBtn':
            obj = self.findChild(QListWidget, 'workList')
            dType = 1
        elif objName == 'saveHolidaysBtn':
            obj = self.findChild(QListWidget, 'holidayList')
            dType = 2
        elif objName == 'savePersonBtn':
            obj = self.findChild(QListWidget, 'personList')
            dType = 3
        else:
            logging.error("非法操作")

        obj.sortItems(0)
        dataList = []
        if obj.count() > 0:
            for i in range(obj.count()):
                str = obj.item(i).text()
                tempList = [str, dType]
                dataList.append(tempList)
        else:
            QMessageBox.warning(self, '警告', '请先输入相关配置信息', QMessageBox.Yes)
            return

        self.logger.info(dataList)
        flag = dbcontrol.saveSetupData(dataList, dType)
        if flag == None:
            QMessageBox.information(self, '消息', f'保存失败！', QMessageBox.Yes)
        else:
            QMessageBox.information(self, '消息', f'成功保存{flag}条数据！', QMessageBox.Yes)

    # 清空
    def clear(self):
        objName = self.sender().objectName()
        if objName == 'workClearBtn':
            obj = self.findChild(QListWidget, 'workList')
        elif objName == 'holidayClearBtn':
            obj = self.findChild(QListWidget, 'holidayList')
        elif objName == 'personClearBtn':
            obj = self.findChild(QListWidget, 'personList')

        obj.clear()

    # 添加设置数据
    def addSetupDate(self):
        objName = self.sender().objectName()
        if objName == 'workCale':
            objList = self.findChild(QListWidget, 'workList')
            obj = self.findChild(QCalendarWidget, objName)
            index = obj.selectedDate().dayOfWeek()
            item = str(obj.selectedDate().toPyDate())
            if index <= 5:
                QMessageBox.warning(self, '警告', f'所选日期{item}已经是工作日了', QMessageBox.Yes)
                return
        elif objName == 'holidayCale':
            objList = self.findChild(QListWidget, 'holidayList')
            obj = self.findChild(QCalendarWidget, objName)
            index = obj.selectedDate().dayOfWeek()
            item = str(obj.selectedDate().toPyDate())
            if index > 5:
                QMessageBox.warning(self, '警告', f'所选日期{item}已经是假期了', QMessageBox.Yes)
                return
        elif objName == 'addPerson':
            objList = self.findChild(QListWidget, 'personList')
            obj = self.findChild(QLineEdit, 'personName')
            item = str(obj.text())
            obj.clear()
        else:
            logging.error("非法操作")

        # 去掉重复的数据
        if objList.count() > 0:
            for i in range(objList.count()):
                t = objList.item(i).text()
                if t == item:
                    QMessageBox.information(self, '消息', f'{item}内容已经存在，请检查后重新输入', QMessageBox.Yes)
                    return

        objList.addItem(item)

    # 删除日期
    def removeDate(self, item):
        objName = self.sender().objectName()
        if objName == 'workList':
            objList = self.findChild(QListWidget, 'workList')
        elif objName == 'holidayList':
            objList = self.findChild(QListWidget, 'holidayList')
        elif objName == 'personList':
            objList = self.findChild(QListWidget, 'personList')
        else:
            logging.error("非法操作")
        # 删除
        if objList.count() > 0:
            for i in range(objList.count()):
                t = objList.item(i).text()
                if t == str(item.text()):
                    objList.takeItem(i)
                    return

    # 选择excel文件
    def select_file(self):
        # 此处编写具体的业务逻辑
        filename, filetype = QtWidgets.QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(),
                                                                   "All Files(*);;Excel files(*.xlsx  *.xls)")
        objName = self.sender().objectName()
        if objName == 'selCheckFile':
            self.ui.checkFilePath.setText(filename)
        else:
            self.ui.restFilePath.setText(filename)
        return

    def __initSetupData(self):

        list = dbcontrol.querySetupData()
        workList = self.findChild(QListWidget, 'workList')
        holidayList = self.findChild(QListWidget, 'holidayList')
        personList = self.findChild(QListWidget, 'personList')
        for i in range(len(list)):
            if list[i]['dtype'] == 1:
                workList.addItem(list[i]['content'])
            elif list[i]['dtype'] == 2:
                holidayList.addItem(list[i]['content'])
            elif list[i]['dtype'] == 3:
                personList.addItem(list[i]['content'])
            else:
                logging.info("非法操作")
        pass

    # 输出结果
    def outputResult(self):
        flag = dbcontrol.outputResult()
        if flag:
            QMessageBox.information(self, '消息', '结果已经正常输出，请前往out路径进行查看', QMessageBox.Yes)
        else:
            QMessageBox.warning(self, '警告', '结果输出异常，请查看具体操作日志', QMessageBox.Yes)
